package org.odst.formula;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class is intended to replace template sheet references with actual sheet references
 * 
 * 
 * @author Cyril PODER
 *
 */

public class TemplateSheetResolver {

    private static final String regexCellRef = "([a-zA-Z]+[a-zA-Z0-9_]*\\.[a-zA-Z|%]+([0-9]+|#)|[a-zA-Z|%]+([0-9]+|#)|'[^?\\\\/:'*]+'\\.[a-zA-Z|%]+([0-9]+|#))";
    private static final Pattern regexCellRefPattern = Pattern.compile( regexCellRef );
    private static final String regexSheetRef = "^([a-zA-Z]+[a-zA-Z0-9_]*)\\.";
    private static final Pattern regexSheetRefPattern = Pattern.compile( regexSheetRef );
    
    public static void updateTemplateSheetRefs(Formula formula, Map<String, List<String>> sheetMapping) {
    	String content = formula.getFormula();
    	Matcher matcher = regexCellRefPattern.matcher(content);
    	while (matcher.find()) {
    		String cellRange = matcher.group();
    		Matcher sheetMatcher = regexSheetRefPattern.matcher(cellRange);
    		if (sheetMatcher.find()) {
    			String templateSheetName = sheetMatcher.group(1);
    			if (sheetMapping.containsKey(templateSheetName)) {
    				Iterator<String> sheetNameIterator = sheetMapping.get(templateSheetName).iterator();
    				String newCellRef = cellRange.replaceAll(templateSheetName, sheetNameIterator.next());
    				while(sheetNameIterator.hasNext())
        				newCellRef += ";" + cellRange.replaceAll(templateSheetName, sheetNameIterator.next());
    				content = content.replace(cellRange, newCellRef);
    				formula.setFormula(content);
    				formula.parseFormula();
    			}
    		}
    	}
	}

}
